﻿using RedLock;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WO.GCode
{
    class GUniqueCodeRedis
    {
        private static readonly object lockTimeCode = new object();
        static RedisHelper helper = new RedisHelper();

        public List<string> GSeqTimeCode(string preCode="",int pCount=1)
        {
            List<string> tmLs = new List<string>();
                 int secondCount = 1;
                 StringBuilder sb = new StringBuilder();

            for (int i = 0; i < pCount; i++)
            {
                sb.Clear();
                string timeCode = preCode+DateTime.Now.ToString("yyyyMMddHHmmss");
                sb.Append(timeCode);
             
                
                lock (lockTimeCode)
                {
                    if (!helper.KeyExists(timeCode))
                    {

                        secondCount = 1;
                        helper.StringSet(timeCode, 1,TimeSpan.FromSeconds(1.1));
                    }
                    else
                    {
                        int count;
                        int.TryParse(helper.StringGet(timeCode),out count);
                        if (count >= 9999)//同个时间如果生成的序号数超过9999,将等待下一秒继续生成编号
                        {
                            while (timeCode == DateTime.Now.ToString("yyyyMMddHHmmss"))
                            {
                                Thread.Sleep(0);
                            }
                            continue;
                        }
                        helper.StringIncrement(timeCode);
                        secondCount = count + 1 ;
                    }

                    string strNo = secondCount.ToString().PadLeft(4, '0');
                    sb.Append(strNo);
                    tmLs.Add(sb.ToString());
               }
            }

            return tmLs;
        }
    }
}
